package statistics;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import util.CommonUtil;
import util.FileUtil;

/**
 * Maintains a map of domains and number of references to them. Allows to export them is a CSV file. 
 * Useful for composing statistical summaries on popularity of resources. 
 */
public class ReferencesCounter implements Counter {
	protected Map<String, Integer> domainRefsCounter;
	
	public ReferencesCounter() {
		domainRefsCounter = new HashMap<String, Integer>();
	}
	
	@Override
	public void incrementCounter(String URL) {
		String key = CommonUtil.getDomainFromLink(URL);
		if (domainRefsCounter.containsKey(key)) {
			int val = (int) domainRefsCounter.get(key);
			domainRefsCounter.put(key, val+1);
		} else {
			domainRefsCounter.put(key, 1);
		}
	}
	
	@Override
	public void resetCounter() {
		this.domainRefsCounter = new HashMap<String, Integer>();
	}
	
	@Override
	public void printCounterStatistics(String folder, String fileName) {
		String contents = "";
		Set<String> keySet = domainRefsCounter.keySet();
		for (String key: keySet) {
			contents+=key+", "+domainRefsCounter.get(key)+"\n";
		}
		if(!FileUtil.pathExists(folder)) {
			FileUtil.createDirectory(folder);
		}
		String filePath = folder+"/"+fileName+".csv";
		FileUtil.saveFile(filePath, contents);
	}
	
	public Map<String, Integer> getDomainRefsCounter() {
		return this.domainRefsCounter;
	}
	
	public void setDomainRefsCounter(Map<String, Integer> counter) {
		this.domainRefsCounter = counter;
	}
}
